package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.entity.CartInfo;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.entity.SkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description 购物车
 * @Return
 * @Author https://weiranyi.github.io
 * @Date Created in 2022-12-17 00:25
 **/
@RequestMapping("/api/cart")
@RestController
public class CartRestController {

    @Autowired
    CartService cartService;

    /**
     * Ajax获取购物车中所有商品列表
     *
     * @return
     */
    @GetMapping("/cartList")
    public Result cartList() {
        // 用哪个购物车
        String cartKey = cartService.determinCaryKey();
        List<CartInfo> cartInfos = cartService.getCartList(cartKey);
        return Result.ok(cartInfos);
    }

    // Ajax修改 http://api.gmall.com/api/cart/addToCart/49/1 POST
    @PostMapping("addToCart/{skuId}/{num}")
    public Result updateCartItemNum(
            @PathVariable("skuId") Long skuId,
            @PathVariable("num") Integer num) {
        // 用哪个购物车
        String cartKey = cartService.determinCaryKey();
        cartService.updateCartItemNum(skuId, num, cartKey);
        return Result.ok();
    }

    // 选中或不选中item
    // http://api.gmall.com/api/cart/checkCart/50/1
    @GetMapping("/checkCart/{skuId}/{status}")
    public Result checkItem(@PathVariable("skuId") Long skuId,
                            @PathVariable("status") Integer status) {
        String cartKey = cartService.determinCaryKey();
        cartService.toggleCartStat(skuId, status, cartKey);
        return Result.ok();
    }

    //删除 http://api.gmall.com/api/cart/deleteCart/50 DELETE
    @DeleteMapping("/deleteCart/{skuId}")
    public Result deleteItem(@PathVariable Long skuId) {
        String cartKey = cartService.determinCaryKey();
        cartService.deleteItem(skuId, cartKey);
        return Result.ok();
    }
}
